Building Selenium Scripts with Python
Building Selenium Scripts means creating Python programs that use Selenium WebDriver to automate web browsers and perform actions such as opening websites, locating web elements, entering data, clicking buttons, navigating between pages, validating results, handling dynamic content, and closing the browser.
A Selenium script generally follows a structured flow: start the WebDriver session, open the application, locate elements, perform actions, validate expected results, handle synchronization and exceptions, and finally close the browser.
Course Resource: Selenium Training | Register for Course Demo
1. What is a Selenium Script?
A Selenium script is a Python program that controls a web browser through Selenium WebDriver. The script can automate repetitive browser tasks and can also be used to execute functional and regression tests against web applications.
Instead of manually opening a browser, navigating to a website, entering information, clicking buttons, and checking results, Selenium allows these operations to be written as executable Python instructions.
Basic Selenium Script Flow
Start
|
v
Import Selenium
|
v
Create WebDriver
|
v
Open Browser
|
v
Navigate to URL
|
v
Locate Web Elements
|
v
Perform Actions
|
v
Validate Results
|
v
Handle Exceptions
|
v
Close Browser
|
v
End
2. Why Build Selenium Scripts?
Selenium scripts are useful when web application testing requires repetitive and reliable browser interactions.
- Automate repetitive browser tasks.
- Reduce manual testing effort.
- Execute functional test cases.
- Support regression testing.
- Validate user workflows.
- Perform data-driven testing.
- Run tests repeatedly.
- Support CI/CD automation.
- Generate repeatable test results.
- Improve test coverage.
3. Components of a Selenium Script
A well-structured Selenium script normally contains several important components.
| Component | Purpose |
| Import statements | Load Selenium and Python libraries. |
| WebDriver | Controls the browser. |
| URL | Specifies the application page. |
| Locators | Identify web elements. |
| WebElement operations | Perform actions such as click and send_keys. |
| Waits | Synchronize the script with application state. |
| Assertions | Validate expected behavior. |
| Exception handling | Manage runtime failures. |
| Logging | Record execution information. |
| Teardown | Close the browser and release resources. |
4. Installing Selenium for Python
The Selenium Python package can be installed using pip. Modern Selenium versions include Selenium Manager, which can automatically manage browser drivers in many common setups.
pip install selenium
To upgrade Selenium:
pip install -U selenium
Verify Installation
python -c "import selenium; print(selenium.__version__)"
5. Creating the First Selenium Script
The first step is to import Selenium and create a browser driver.
from selenium import webdriver
driver = webdriver.Chrome()
The Selenium Python API supports creating a Chrome WebDriver directly with webdriver.Chrome(). Selenium Manager can handle driver management for typical installations.
6. Opening a Website
The get() method navigates the browser to a specified URL.
from selenium import webdriver
driver = webdriver.Chrome()
try:
driver.get("https://example.com")
finally:
driver.quit()
7. Understanding driver.get()
The driver.get() method instructs WebDriver to navigate to the specified URL.
driver.get("https://www.selenium.dev")
A Selenium script can navigate to login pages, dashboards, product pages, search pages, checkout pages, administration panels, and other web application URLs.
8. Getting the Page Title
The title property can be used to retrieve the current browser page title.
title = driver.title
print(title)
Title Validation
assert "Selenium" in driver.title
Assertions are useful for verifying that the application reached the expected page.
9. Getting the Current URL
print(driver.current_url)
URL validation can be useful after navigation or login.
assert "/dashboard" in driver.current_url
10. Finding Web Elements
Most Selenium scripts interact with web elements. Before performing an action, the script normally needs to locate the required element. Selenium's Python API uses find_element() together with the By locator strategies.
from selenium.webdriver.common.by import By
username = driver.find_element(By.ID, "username")
11. Common Selenium Locators
| Locator | Example |
| ID | By.ID, "username" |
| NAME | By.NAME, "email" |
| CLASS_NAME | By.CLASS_NAME, "login-button" |
| TAG_NAME | By.TAG_NAME, "button" |
| LINK_TEXT | By.LINK_TEXT, "Login" |
| PARTIAL_LINK_TEXT | By.PARTIAL_LINK_TEXT, "Log" |
| CSS_SELECTOR | By.CSS_SELECTOR, "#username" |
| XPATH | By.XPATH, "//input[@id='username']" |
12. Using ID Locator
username = driver.find_element(
By.ID,
"username"
)
username.send_keys("admin")
13. Using Name Locator
email = driver.find_element(
By.NAME,
"email"
)
email.send_keys("[email protected]")
14. Using CSS Selector
login_button = driver.find_element(
By.CSS_SELECTOR,
"button.login"
)
login_button.click()
15. Using XPath
login_button = driver.find_element(
By.XPATH,
"//button[@id='login']"
)
login_button.click()
16. Entering Text with send_keys()
The send_keys() method enters text into an input field.
username = driver.find_element(By.ID, "username")
username.send_keys("admin")
17. Clearing Input Fields
username.clear()
username.send_keys("new_user")
18. Clicking Elements
login_button = driver.find_element(
By.ID,
"login"
)
login_button.click()
19. Reading Element Text
message = driver.find_element(
By.ID,
"message"
)
print(message.text)
20. Reading Attributes
value = element.get_attribute("value")
print(value)
For example:
placeholder = driver.find_element(
By.ID,
"username"
).get_attribute("placeholder")
print(placeholder)
21. Checking Element State
element = driver.find_element(By.ID, "submit")
print(element.is_displayed())
print(element.is_enabled())
print(element.is_selected())
22. Building a Simple Login Script
A login automation script generally performs the following sequence:
Open Login Page
|
v
Find Username
|
v
Enter Username
|
v
Find Password
|
v
Enter Password
|
v
Find Login Button
|
v
Click Login
|
v
Wait for Dashboard
|
v
Validate Login
|
v
Close Browser
Login Script
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
try:
driver.get("https://example.com/login")
username = driver.find_element(
By.ID,
"username"
)
password = driver.find_element(
By.ID,
"password"
)
login_button = driver.find_element(
By.ID,
"login"
)
username.send_keys("admin")
password.send_keys("admin123")
login_button.click()
print("Login action completed")
finally:
driver.quit()
23. Using Waits in Selenium Scripts
Modern web applications frequently load content asynchronously. Therefore, a Selenium script should synchronize its actions with the state of the browser rather than assuming that every element is immediately ready.
Explicit Wait Example
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
login_button = WebDriverWait(
driver,
10
).until(
EC.element_to_be_clickable(
(By.ID, "login")
)
)
login_button.click()
24. Why Explicit Waits are Useful
- Handle dynamic elements.
- Reduce timing-related failures.
- Wait for specific application conditions.
- Improve script reliability.
- Avoid unnecessary fixed delays.
25. Avoiding Hardcoded sleep()
A fixed sleep pauses for a predetermined amount of time regardless of whether the application is ready.
import time
time.sleep(5)
driver.find_element(
By.ID,
"login"
).click()
A condition-based wait is generally more appropriate when the required application state can be expressed explicitly.
login = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable(
(By.ID, "login")
)
)
login.click()
26. Using Assertions
Assertions verify whether the actual result matches the expected result.
assert "Dashboard" in driver.title
Message Assertion
message = driver.find_element(
By.ID,
"message"
).text
assert message == "Login successful"
27. Soft Validation with Conditions
if "Dashboard" in driver.current_url:
print("Login successful")
else:
print("Login failed")
In a real test framework, assertions are normally preferred when the condition represents a required test result.
28. Handling Checkboxes
terms = driver.find_element(
By.ID,
"terms"
)
if not terms.is_selected():
terms.click()
29. Handling Radio Buttons
male = driver.find_element(
By.ID,
"male"
)
if not male.is_selected():
male.click()
30. Handling Dropdowns
For a standard HTML <select> element, Selenium provides the Select helper.
from selenium.webdriver.support.ui import Select
country = Select(
driver.find_element(By.ID, "country")
)
country.select_by_visible_text("India")
Other selection methods include:
country.select_by_value("in")
country.select_by_index(0)
31. Handling Keyboard Actions
from selenium.webdriver.common.keys import Keys
search = driver.find_element(
By.NAME,
"q"
)
search.send_keys("Selenium")
search.send_keys(Keys.ENTER)
32. Handling Links
documentation = driver.find_element(
By.LINK_TEXT,
"Documentation"
)
documentation.click()
33. Handling Multiple Elements
Use find_elements() when multiple matching elements are expected.
products = driver.find_elements(
By.CLASS_NAME,
"product"
)
print("Products:", len(products))
for product in products:
print(product.text)
34. Finding Child Elements
form = driver.find_element(
By.ID,
"login-form"
)
inputs = form.find_elements(
By.TAG_NAME,
"input"
)
for field in inputs:
print(field.get_attribute("name"))
35. Navigation Commands
Selenium scripts can navigate between pages using browser navigation commands.
driver.get("https://example.com")
driver.back()
driver.forward()
driver.refresh()
36. Opening a New URL
driver.get(
"https://example.com/products"
)
37. Browser Window Management
driver.maximize_window()
Other useful operations include:
driver.minimize_window()
driver.fullscreen_window()
38. Window Handles
print(driver.current_window_handle)
print(driver.window_handles)
Switching Windows
original_window = driver.current_window_handle
for handle in driver.window_handles:
if handle != original_window:
driver.switch_to.window(handle)
break
39. Handling Frames
When a web element exists inside an iframe, the script must switch into the appropriate frame before interacting with its contents.
driver.switch_to.frame(
driver.find_element(
By.ID,
"payment-frame"
)
)
card = driver.find_element(
By.ID,
"card-number"
)
card.send_keys("4111111111111111")
driver.switch_to.default_content()
Using Explicit Wait with Frame
WebDriverWait(driver, 10).until(
EC.frame_to_be_available_and_switch_to_it(
(By.ID, "payment-frame")
)
)
40. Handling Alerts
alert = driver.switch_to.alert
print(alert.text)
alert.accept()
Dismiss Alert
alert.dismiss()
Enter Alert Text
alert.send_keys("Test data")
alert.accept()
41. Waiting for an Alert
alert = WebDriverWait(driver, 10).until(
EC.alert_is_present()
)
alert.accept()
42. Handling Cookies
driver.add_cookie({
"name": "test_cookie",
"value": "selenium"
})
Get Cookies
cookies = driver.get_cookies()
for cookie in cookies:
print(cookie)
Delete Cookies
driver.delete_all_cookies()
43. JavaScript Execution
Selenium scripts can execute JavaScript when browser-level interaction requires it.
title = driver.execute_script(
"return document.title;"
)
print(title)
Scroll Page
driver.execute_script(
"window.scrollTo(0, document.body.scrollHeight);"
)
Scroll to Element
element = driver.find_element(
By.ID,
"footer"
)
driver.execute_script(
"arguments[0].scrollIntoView();",
element
)
JavaScript should generally complement normal Selenium interactions rather than automatically replacing them.
44. Taking Screenshots
Screenshots are useful when debugging failed automation steps.
driver.save_screenshot(
"homepage.png"
)
Screenshot on Failure
try:
driver.find_element(
By.ID,
"submit"
).click()
except Exception:
driver.save_screenshot(
"failure.png"
)
raise
45. Exception Handling in Selenium Scripts
Selenium scripts interact with browsers and dynamic applications, so exceptions can occur during element lookup, interaction, synchronization, frame switching, window switching, and browser operations.
from selenium.common.exceptions import (
NoSuchElementException,
TimeoutException,
WebDriverException
)
try:
element = WebDriverWait(
driver,
10
).until(
EC.element_to_be_clickable(
(By.ID, "submit")
)
)
element.click()
except TimeoutException:
print("Element did not become clickable")
except NoSuchElementException:
print("Element was not found")
except WebDriverException as e:
print("WebDriver error:", e)
46. Using finally for Browser Cleanup
driver = None
try:
driver = webdriver.Chrome()
driver.get("https://example.com")
# Test steps
finally:
if driver:
driver.quit()
Calling quit() ends the WebDriver session and closes the browser session.
47. Logging Selenium Script Execution
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.info("Starting Selenium script")
driver = webdriver.Chrome()
logging.info("Browser started")
driver.get("https://example.com")
logging.info("Application opened")
48. Logging Test Steps
logging.info("Entering username")
username.send_keys("admin")
logging.info("Entering password")
password.send_keys("admin123")
logging.info("Clicking login button")
login_button.click()
logging.info("Login operation completed")
49. Building a Complete Selenium Script
A professional Selenium script should combine browser initialization, navigation, locators, actions, waits, validation, exception handling, logging, screenshots, and cleanup.
import logging
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import (
TimeoutException,
WebDriverException
)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
driver = None
try:
logging.info("Starting browser")
driver = webdriver.Chrome()
driver.get(
"https://example.com/login"
)
wait = WebDriverWait(driver, 10)
logging.info("Finding username field")
username = wait.until(
EC.visibility_of_element_located(
(By.ID, "username")
)
)
logging.info("Finding password field")
password = wait.until(
EC.visibility_of_element_located(
(By.ID, "password")
)
)
logging.info("Finding login button")
login_button = wait.until(
EC.element_to_be_clickable(
(By.ID, "login")
)
)
username.send_keys("admin")
password.send_keys("admin123")
login_button.click()
wait.until(
EC.url_contains("/dashboard")
)
assert "/dashboard" in driver.current_url
logging.info(
"Login test completed successfully"
)
except TimeoutException as e:
logging.error(
"Timeout occurred: %s",
e
)
if driver:
driver.save_screenshot(
"timeout_failure.png"
)
except WebDriverException as e:
logging.error(
"WebDriver error: %s",
e
)
if driver:
driver.save_screenshot(
"webdriver_failure.png"
)
finally:
if driver:
driver.quit()
logging.info("Browser closed")
50. Building a Search Script
A search automation script typically opens a search page, enters a search term, submits the search, waits for results, and validates the results.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
try:
driver.get(
"https://example.com/search"
)
search_box = WebDriverWait(
driver,
10
).until(
EC.visibility_of_element_located(
(By.NAME, "q")
)
)
search_box.clear()
search_box.send_keys(
"Selenium Python"
)
search_box.send_keys(Keys.ENTER)
results = WebDriverWait(
driver,
10
).until(
EC.presence_of_all_elements_located(
(By.CSS_SELECTOR, ".result")
)
)
print("Results:", len(results))
finally:
driver.quit()
51. Building an E-Commerce Selenium Script
An e-commerce workflow can be automated by creating a sequence of browser operations.
Open Website
|
v
Login
|
v
Search Product
|
v
Select Product
|
v
Add to Cart
|
v
Open Cart
|
v
Verify Product
|
v
Proceed to Checkout
|
v
Verify Checkout
|
v
Logout
Example
search = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located(
(By.ID, "search")
)
)
search.send_keys("Laptop")
search.send_keys(Keys.ENTER)
product = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, ".product-card")
)
)
product.click()
add_to_cart = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable(
(By.ID, "add-to-cart")
)
)
add_to_cart.click()
52. Building a Registration Script
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
try:
driver.get(
"https://example.com/register"
)
driver.find_element(
By.ID,
"name"
).send_keys("John")
driver.find_element(
By.ID,
"email"
).send_keys("[email protected]")
driver.find_element(
By.ID,
"password"
).send_keys("Password123")
driver.find_element(
By.ID,
"confirm-password"
).send_keys("Password123")
driver.find_element(
By.ID,
"register"
).click()
finally:
driver.quit()
53. Building a Reusable Function
Instead of repeating the same Selenium operations throughout a project, common actions can be placed into reusable functions.
def enter_text(driver, locator, value):
element = WebDriverWait(
driver,
10
).until(
EC.visibility_of_element_located(locator)
)
element.clear()
element.send_keys(value)
Using the Function
enter_text(
driver,
(By.ID, "username"),
"admin"
)
enter_text(
driver,
(By.ID, "password"),
"admin123"
)
54. Reusable Click Function
def click_element(driver, locator):
element = WebDriverWait(
driver,
10
).until(
EC.element_to_be_clickable(locator)
)
element.click()
Using the Function
click_element(
driver,
(By.ID, "login")
)
55. Page Object Model
The Page Object Model, commonly called POM, separates page-specific locators and interactions from test logic. This reduces duplication and makes large Selenium projects easier to maintain.
Example Login Page
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class LoginPage:
USERNAME = (By.ID, "username")
PASSWORD = (By.ID, "password")
LOGIN_BUTTON = (By.ID, "login")
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(
driver,
10
)
def login(self, username, password):
self.wait.until(
EC.visibility_of_element_located(
self.USERNAME
)
).send_keys(username)
self.wait.until(
EC.visibility_of_element_located(
self.PASSWORD
)
).send_keys(password)
self.wait.until(
EC.element_to_be_clickable(
self.LOGIN_BUTTON
)
).click()
56. Test Using Page Object
def test_login(driver):
login_page = LoginPage(driver)
login_page.login(
"admin",
"admin123"
)
assert "/dashboard" in driver.current_url
57. Using pytest with Selenium
Pytest is commonly used as a Python test runner for organizing and executing Selenium test cases.
Installation
pip install pytest
Simple Test
from selenium import webdriver
def test_homepage_title():
driver = webdriver.Chrome()
try:
driver.get(
"https://example.com"
)
assert "Example" in driver.title
finally:
driver.quit()
Pytest can be used to organize Selenium tests into maintainable test suites.
58. Using pytest Fixtures
Fixtures can be used to create and clean up browser sessions.
import pytest
from selenium import webdriver
@pytest.fixture
def driver():
browser = webdriver.Chrome()
yield browser
browser.quit()
Using the Fixture
def test_title(driver):
driver.get(
"https://example.com"
)
assert "Example" in driver.title
59. Separating Test Data
Test data should ideally be separated from test logic when the same workflow needs to run with multiple datasets.
users = [
("admin", "admin123"),
("user1", "user123"),
("tester", "test123")
]
for username, password in users:
print(username, password)
60. Data-Driven Selenium Concept
Test Data
|
+-- User 1
|
+-- User 2
|
+-- User 3
|
v
Same Selenium Workflow
|
v
Different Test Results
61. Organizing Selenium Scripts
Small Selenium scripts can be maintained in a single Python file, but larger automation projects should separate tests, page objects, utilities, configuration, test data, screenshots, and reports.
Suggested Project Structure
selenium_project/
|
+-- tests/
| +-- test_login.py
| +-- test_search.py
| +-- test_cart.py
|
+-- pages/
| +-- login_page.py
| +-- home_page.py
| +-- product_page.py
| +-- cart_page.py
|
+-- utilities/
| +-- wait_helper.py
| +-- screenshot_helper.py
| +-- logger.py
|
+-- test_data/
| +-- users.json
| +-- products.json
|
+-- screenshots/
|
+-- reports/
|
+-- conftest.py
|
+-- requirements.txt
62. requirements.txt
selenium
pytest
Install project dependencies with:
pip install -r requirements.txt
63. Building a Selenium Script Step by Step
- Install Python.
- Install Selenium.
- Install a supported browser.
- Create a Python file.
- Import Selenium.
- Create the WebDriver.
- Open the application URL.
- Identify required web elements.
- Select stable locators.
- Add appropriate waits.
- Perform browser actions.
- Validate expected results.
- Add exception handling.
- Add logging and screenshots.
- Close the browser.
- Execute the script using Python or a test runner.
64. Complete Script Development Flow
Requirement
|
v
Test Scenario
|
v
Test Steps
|
v
Identify Web Elements
|
v
Choose Locators
|
v
Write Selenium Commands
|
v
Add Wait Strategy
|
v
Add Assertions
|
v
Add Exception Handling
|
v
Add Logging
|
v
Execute Test
|
v
Analyze Result
|
v
Maintain Script
65. Common Mistakes While Building Selenium Scripts
Mistake 1: Using Incorrect Locators
driver.find_element(
By.ID,
"wrong-id"
)
Always verify that the locator actually identifies the intended element.
Mistake 2: Using Hardcoded Delays Everywhere
time.sleep(10)
Prefer condition-based waits when the required browser state can be defined.
Mistake 3: Ignoring Dynamic Content
Modern applications can update the DOM after the initial page load. Scripts should account for these state changes.
Mistake 4: Using Unstable XPath
/html/body/div[2]/div[3]/div[1]/button
Long positional XPath expressions can be fragile when the page structure changes.
Mistake 5: Not Closing the Browser
driver = webdriver.Chrome()
driver.get("https://example.com")
# No cleanup
Use appropriate teardown or finally logic.
Mistake 6: Catching Every Exception
try:
...
except:
pass
This can hide important failures and make debugging difficult.
Mistake 7: Putting Everything in One Large Function
Large scripts become difficult to maintain. Use functions, page objects, utilities, and test fixtures as the project grows.
66. Best Practices for Building Selenium Scripts
- Use meaningful variable and function names.
- Use stable locators.
- Prefer explicit waits for dynamic conditions.
- Avoid unnecessary hardcoded sleeps.
- Keep test data separate from automation logic.
- Use Page Object Model for larger projects.
- Use reusable helper functions.
- Use assertions for important expected results.
- Handle exceptions appropriately.
- Capture screenshots for important failures.
- Use logging instead of relying only on print statements.
- Keep browser cleanup in teardown or finally blocks.
- Do not silently ignore exceptions.
- Keep tests independent where practical.
- Use a test runner for larger test suites.
- Keep the automation project organized.
- Review and maintain locators when the UI changes.
67. Good Script vs Poor Script
| Poor Practice | Better Practice |
| Long hardcoded XPath | Stable ID, name, CSS, or concise XPath |
| Repeated code | Reusable functions or page objects |
| Only sleep() | Condition-based waits |
| No assertions | Validate expected results |
| Empty except block | Log or properly handle exceptions |
| No cleanup | Use teardown or finally |
| One huge script | Modular project structure |
| Hardcoded test data everywhere | Separate test data |
68. Practical Project: Automated Login Test
Create a complete Selenium Python script that tests a login workflow.
Requirements
- Open the login page.
- Verify the page title.
- Locate the username field.
- Locate the password field.
- Enter valid credentials.
- Click the login button.
- Wait for the dashboard.
- Verify the dashboard URL or heading.
- Capture a screenshot if the test fails.
- Close the browser.
Expected Flow
Open Login Page
|
v
Verify Title
|
v
Enter Username
|
v
Enter Password
|
v
Click Login
|
v
Wait for Dashboard
|
v
Validate Dashboard
|
v
Pass / Fail
|
v
Cleanup
69. Practical Project: Automated Search Test
Build a search automation script that:
- Opens the website.
- Finds the search box.
- Enters a search term.
- Submits the search.
- Waits for search results.
- Counts result elements.
- Validates that results are displayed.
- Captures a screenshot on failure.
70. Practical Project: E-Commerce Cart Test
Create a script that automates a complete shopping workflow.
Open Store
|
v
Login
|
v
Search Product
|
v
Open Product
|
v
Add Product to Cart
|
v
Open Cart
|
v
Verify Product
|
v
Verify Quantity
|
v
Verify Price
|
v
Proceed to Checkout
71. Practical Project: Registration Test
Automate a registration form containing:
- First name.
- Last name.
- Email.
- Password.
- Confirm password.
- Gender.
- Country.
- Terms checkbox.
- Register button.
The script should validate the success message after registration.
72. Practical Project: Complete Regression Workflow
A larger Selenium project can combine multiple workflows.
Test Suite
|
+-- Login Test
|
+-- Search Test
|
+-- Product Test
|
+-- Cart Test
|
+-- Checkout Test
|
+-- Logout Test
|
v
Generate Test Results
73. Selenium Script Execution
A standalone Python Selenium script can be executed from the terminal using Python.
python test_login.py
For pytest-based projects:
pytest test_login.py
74. Debugging Selenium Scripts
When a Selenium script fails, investigate the failure systematically.
- Read the exception message.
- Identify the failing line.
- Check the current URL.
- Check the page title.
- Inspect the HTML element.
- Verify the locator.
- Check whether a frame is involved.
- Check whether a new window is involved.
- Check whether an alert is blocking the page.
- Check the synchronization strategy.
- Capture a screenshot.
- Review logs.
Useful Debug Information
print("URL:", driver.current_url)
print("Title:", driver.title)
print("Handles:", driver.window_handles)
print("Source length:", len(driver.page_source))
75. Selenium Script Maintenance
Web applications change frequently. A locator that works today may stop working after a UI redesign. Therefore, Selenium scripts require regular maintenance.
Maintenance Checklist
- Review broken locators.
- Remove duplicate code.
- Update waits when application behavior changes.
- Remove obsolete test data.
- Update browser and Selenium versions as required.
- Review exception handling.
- Review screenshots and logs.
- Remove unnecessary workarounds.
- Keep Page Objects synchronized with the application.
76. Interview Questions on Building Selenium Scripts
Q1. What is a Selenium script?
A Selenium script is a program that uses Selenium WebDriver to automate browser interactions and validate web application behavior.
Q2. What are the basic steps of a Selenium script?
Start the WebDriver, open the URL, locate elements, perform actions, validate results, handle failures, and close the browser.
Q3. How do you launch Chrome using Selenium Python?
from selenium import webdriver
driver = webdriver.Chrome()
Q4. How do you open a website?
driver.get("https://example.com")
Q5. How do you locate an element?
element = driver.find_element(
By.ID,
"username"
)
Q6. How do you enter text?
element.send_keys("Selenium")
Q7. How do you click a button?
button.click()
Q8. How do you retrieve element text?
print(element.text)
Q9. Why are waits important?
Waits synchronize the script with the application's current browser state and reduce failures caused by timing differences.
Q10. What is Page Object Model?
POM is a design approach that organizes page locators and page interactions into dedicated classes.
Q11. Why use assertions?
Assertions verify whether actual application behavior matches the expected result.
Q12. Why use finally?
The finally block can be used to ensure browser cleanup occurs whether the script succeeds or fails.
Q13. What is the difference between close() and quit()?
close() closes the current browser window or tab, while quit() ends the WebDriver session and closes the browser session.
Q14. How do you handle a dynamic element?
Use an appropriate locator and synchronization strategy, commonly an explicit wait for the required condition.
Q15. How do you make Selenium scripts maintainable?
Use stable locators, reusable functions, Page Object Model, test data separation, explicit waits, logging, exception handling, and a structured project layout.
77. Quick Revision Table
| Command / Concept | Purpose |
webdriver.Chrome() | Creates Chrome WebDriver. |
driver.get() | Opens a URL. |
driver.title | Returns page title. |
driver.current_url | Returns current URL. |
find_element() | Finds one element. |
find_elements() | Finds multiple elements. |
send_keys() | Enters text or keyboard commands. |
click() | Clicks an element. |
clear() | Clears an input. |
text | Gets rendered element text. |
get_attribute() | Gets an element attribute/property value. |
WebDriverWait | Waits for a condition. |
EC | Provides expected conditions. |
assert | Validates expected behavior. |
save_screenshot() | Captures browser screenshot. |
driver.quit() | Ends the WebDriver session. |
78. Recommended Selenium Script Structure
Imports
|
v
Configuration
|
v
Driver Setup
|
v
Test Data
|
v
Open Application
|
v
Page Interaction
|
v
Synchronization
|
v
Validation
|
v
Exception Handling
|
v
Logging
|
v
Screenshot on Failure
|
v
Teardown
79. Professional Selenium Automation Flow
Requirement
|
v
Test Case Design
|
v
Python Test Script
|
v
Page Objects
|
v
Reusable Utilities
|
v
WebDriver
|
v
Browser
|
v
Web Application
|
v
Expected Result
|
v
Assertion
|
+------ Pass
|
+------ Fail
|
v
Log + Screenshot
|
v
Test Report
80. Final Summary
Building Selenium Scripts with Python involves much more than simply opening a browser and clicking elements. A reliable Selenium script combines WebDriver initialization, navigation, element location, browser and element operations, synchronization, validation, exception handling, logging, screenshots, and cleanup.
Selenium scripting commonly involves starting the browser session, navigating to a page, finding elements, performing actions, requesting browser or element information, establishing a waiting strategy, validating results, and ending the session.
For small automation tasks, a simple Python script may be sufficient. For larger projects, the script should be organized using Page Object Model, reusable utilities, fixtures, test data, logging, reporting, and a structured project architecture.
The main goal of professional Selenium scripting is to create automation that is reliable, readable, reusable, maintainable, debuggable, and scalable.
81. Course Resources
Selenium Training: https://www.justacademy.co/course-detail/selenium-training
Register for Course Demo: https://www.justacademy.co/register-for-course-demo